import json
import os
from global_settings import debug_print

class ConfigManager:
    def __init__(self, config_file="config.json"):
        self.config_file = config_file

    def load_config(self):
        """加载配置"""
        default_config = {
            'serial': {
                'port': '',
                'baudrate': '9600',
                'databits': '8',
                'stopbits': '1',
                'parity': 'N'
            },
            'protocol': {
                'current': 'default.json'
            }
        }

        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                    debug_print(f"配置文件加载成功: {self.config_file}")
                    return config
            except json.JSONDecodeError as e:
                debug_print(f"配置文件解析失败: {str(e)}")
                return default_config
            except Exception as e:
                debug_print(f"配置文件加载异常: {str(e)}")
                return default_config
        else:
            debug_print(f"配置文件不存在，使用默认配置: {self.config_file}")
            return default_config

    def save_config(self, config):
        """保存配置"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=4, ensure_ascii=False)
        except Exception as e:
            debug_print(f"保存配置失败: {str(e)}")